import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hall/const_config.dart';
import 'package:flutter_hall/utils.dart';
import 'package:share_plus/share_plus.dart';

import 'eventbus.dart';
import 'lines.dart';

class LaboratoryPage extends StatefulWidget {
  const LaboratoryPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LaboratoryState();
  }
}

class _LaboratoryState extends State<LaboratoryPage> {
  bool _switchValue = ConstConfig.GPSState;
  final List locations = [];
  int _count = 0;
  final timeout = const Duration(seconds: 10);
  Timer? timer;

  final Storage _storage = Storage();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          systemOverlayStyle: const SystemUiOverlayStyle(
              systemNavigationBarColor: Colors.black,
              systemNavigationBarDividerColor: null,
              statusBarColor: null,
              systemNavigationBarIconBrightness: Brightness.light,
              statusBarIconBrightness: Brightness.dark,
              statusBarBrightness: Brightness.light),
          elevation: 0.3,
          backgroundColor: Colors.white,
          iconTheme: const IconThemeData(color: Colors.black, opacity: 0.8),
          actions: [
            IconButton(
                onPressed: () {
                  _history();
                },
                icon: const Icon(Icons.history)),
            IconButton(
                disabledColor: Colors.grey,
                onPressed: !_switchValue && _count > 1
                    ? () {
                        _localMap();
                      }
                    : null,
                icon: const Icon(Icons.local_library)),
          ],
        ),
        backgroundColor: Colors.white,
        body: Container(
          padding: const EdgeInsets.only(top: 20, left: 10, right: 10),
          child: Flex(
            direction: Axis.vertical,
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 10, bottom: 12),
                child: CircleAvatar(
                  radius: 40,
                  child: Text(_count.toString()),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('开启采集'),
                  Switch(
                      value: _switchValue,
                      onChanged: (bll) {
                        setState(() {
                          _switchValue = !_switchValue;
                          ConstConfig.GPSState = _switchValue;
                        });
                        bus.emit("onTrack", _switchValue);
                      }),
                ],
              ),
              Flex(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                direction: Axis.horizontal,
                children: [
                  MaterialButton(
                    disabledColor: Colors.grey,
                    onPressed: _switchValue
                        ? null
                        : () {
                            _storage.clearData();
                            setState(() {
                              _count = 0;
                            });
                          },
                    child: const Text(
                      '清空',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Colors.blue,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 4, right: 4),
                    child: MaterialButton(
                      disabledColor: Colors.grey,
                      onPressed: _switchValue
                          ? null
                          : () {
                              _share();
                            },
                      child: const Text(
                        '共享',
                        style: TextStyle(color: Colors.white),
                      ),
                      color: Colors.blue,
                    ),
                  ),
                  MaterialButton(
                    disabledColor: Colors.grey,
                    onPressed: _switchValue
                        ? null
                        : () {
                            _inCome();
                          },
                    child: const Text(
                      '导入',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Colors.blue,
                  ),
                ],
              )
            ],
          ),
        ));
  }

  @override
  void dispose() {
    super.dispose();
    if (timer != null) {
      timer!.cancel();
    }
  }

  @override
  void initState() {
    super.initState();
    getCount();
    Timer.periodic(timeout, (timers) {
      timer = timers;
      getCount();
    });
  }

  void _share() async {
    final box = context.findRenderObject() as RenderBox?;
    String path = await _storage.getPath();
    Share.shareFiles([path],
            text: '文件分享',
            subject: '共享文件',
            sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size)
        .then((value) => {});
  }

  void getCount() {
    Utils.getMyLine().then((value) => {
          if (mounted)
            {
              setState(() {
                _count = value.length;
              })
            }
        });
  }

  void _localMap() {
    bus.emit('drawLine', 1);
    Navigator.pop(context);
  }

  void _inCome() async {
    // FilePickerResult? result = await FilePicker.platform.pickFiles(
    //     type: FileType.custom,
    //     allowedExtensions: ['txt'],
    //     allowMultiple: false);
    // if (result != null) {
    //   List<String?> ll = result.paths;
    //   if (ll.length == 1) {
    //     String? path = ll[0];
    //     if (path != null) {
    //       File file = File(path);
    //       String data = file.readAsStringSync();
    //       Storage().writeCounter(data, mode: FileMode.write);
    //     }
    //   }
    // }
  }

  void _history() {
    Navigator.push(context, MaterialPageRoute(builder: (context) => LinePage()))
        .then((value) => {Navigator.pop(context, value)});
  }
}
